package com.jams.goodox.activity.serve.tenement;

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.entity.TenementMonthBean;
import com.jams.goodox.entity.TenementProductBean;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.MaxListView;
import com.jams.goodox.widget.NoScrollListView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

import static com.jams.goodox.utils.Utils.AddTwoValue;
import static com.jams.goodox.utils.Utils.SubtractTwoValue;

/**
 *  物业缴费月账单
 * Created by jams_zhen on 2016/9/23.
 */

public class TenementMonthActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.lst)
    ListView lst;
    @Bind(R.id.tx_chooseChild)
    TextView txChooseChild;
    @Bind(R.id.tx_needPay)
    TextView txNeedPay;
    @Bind(R.id.img_check)
    ImageView imgCheck;
    @Bind(R.id.tx_goPay)
    TextView tx_goPay;

    private Intent in;
    private ListCommonAdapter listCommonAdapter;
    private ListCommonAdapter secCommonAdapter;
    private List<TenementMonthBean.DataBean> topList;

    private double addPrice = 0;
    private int chooseNum = 0;
    private int allNum = 0;

    private int year;
    DecimalFormat decimalFormat;

    private PopupWindow popupWindow;//筛选弹框
    private ListCommonAdapter screenAdapter;//筛选列表适配器
    private List<TenementProductBean.DataBean> screenLst;//筛选数据源

    private String barTitle;//标题

    private int typePsi = -1;//筛选选中项


    @Override
    protected int getLayoutId() {
        return R.layout.tenement_month_activity;
    }

    @Override
    protected void init() {
        getFromData();
        //标题及左右ui
//        StyleUtil.titleBothIconListener(this, barTitle,this, R.mipmap.title_screen, this);
        StyleUtil.titleBackKey(this,barTitle);

        decimalFormat = new DecimalFormat("#0.00");
        tx_goPay.setText("选好了");
        //字体标红
        txNeedPay.setText(Html.fromHtml("<font color=#666666>" + "合计：" + "</font>"
                + "<font color=#ff6e0b>" + "¥0.00" + "</font>"));

        setData();
        getData();
        //初始化筛选框
        initPopWin();
//        getTenementType();
    }

    /**
     * 获取上个页面传递的数据
     */
    private void getFromData(){
        in = getIntent();
        barTitle = in.getStringExtra("title") + "明细";
        allNum = in.getIntExtra("typeNeedPayNum", 0);
        chooseNum = in.getIntExtra("chooseNum", 0);
        addPrice = in.getDoubleExtra("addPrice", 0);
        year = in.getIntExtra("year", 0);
        typePsi=in.getIntExtra("typePsi", 0);
    }

    /**
     * 初始化pop，此处要求bar和列表颜色一致，所以pop直接全部替换包括bar
     */
    private void initPopWin() {
        View view = getLayoutInflater().inflate(R.layout.list_tenement_screen, null);
        MaxListView screenListView = (MaxListView) view.findViewById(R.id.screen_list);
        screenListView.setListViewHeight(getResources().getDimensionPixelOffset(R.dimen.screen_list_max_height));
        screenLst = new ArrayList<>();
        screenAdapter = new ListCommonAdapter<TenementProductBean.DataBean>(this, screenLst, R.layout.item_screen_tenement) {
            @Override
            public void convert(ListCommonViewHolder helper, TenementProductBean.DataBean item, int position) {
                ((TextView) helper.getView(R.id.tx_screen)).setText(item.getName());
                helper.getView(R.id.img_check).setVisibility(item.isChoose() ? View.VISIBLE : View.GONE);
            }
        };
        screenListView.setAdapter(screenAdapter);
        screenListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (typePsi >= 0)
                    screenLst.get(typePsi).setChoose(false);
                screenLst.get(position).setChoose(true);
                screenAdapter.notifyDataSetChanged();
                //此处：选中勾，重置数据
                typePsi = position;
                searchMonthData(screenLst.get(position).getCode(),true);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.view_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
    }

    @OnClick({R.id.tx_goPay, R.id.img_check,R.id.ler_back,R.id.ler_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx_goPay:
                if(topList==null||topList.size()==0)return;//此处如果列表为空不允许点击选好了，主要是避免筛选&网络请求失败的异常处理
                in = new Intent();
                in.putExtra("num", chooseNum);
                in.putExtra("typeNeedPayNum",allNum);
                in.putExtra("money", addPrice);
                in.putExtra("monthList", (Serializable) topList);
                in.putExtra("typePsi",typePsi);
                setResult(RESULT_OK, in);
                finish();
                break;
            case R.id.img_check:
                //如果选中，变为不选中
                if (chooseNum == allNum) {
                    chooseNum = 0;
                    addPrice = 0;
                    setChooseDo(false);//勾选取消
                    setChoose();//底部值计算
                } else {
                    chooseNum = allNum;
                    setChooseDo(true);//勾选所有
                    setChoose();//底部值计算
                }
                break;
//            case R.id.ler_back://重写返回键点击事件
//                if(popupWindow!=null&&popupWindow.isShowing())
//                    popupWindow.dismiss();
//                else finish();
//                break;
//            case R.id.ler_save:
//                if (popupWindow == null) return;
//                if (!popupWindow.isShowing()) {
//                    //此处修复7.0 popwinDow弹出位置错乱的问题
//                    if (android.os.Build.VERSION.SDK_INT >= 24) {
//                        popupWindow.showAtLocation(getTitleBar(), Gravity.NO_GRAVITY,0, DeviceUtils.getStatusBarHeight(mContext)+getTitleBar().getHeight());
//                    } else {
//                        popupWindow.showAsDropDown(getTitleBar());
//                    }
//                } else {
//                    popupWindow.dismiss();
//                }
//                break;
        }
    }

    /**
     * 获取物业缴费类型
     */
    private void getTenementType() {
        HashMap<String, String> map = new HashMap<>();
        map.put("billYear", year + "");
        enqueue(createCallService(ServiceService.class).getTenementType(map), new RetrofitCallbackListener<TenementProductBean>() {
            @Override
            public void onSuccess(Call<TenementProductBean> call, TenementProductBean tenementMonthBean) {
                misLoading();
                if (tenementMonthBean.getData() == null || tenementMonthBean.getData().size() == 0)
                    return;
                if(tenementMonthBean.getData().size()>typePsi)tenementMonthBean.getData().get(typePsi).setChoose(true);
                screenLst.addAll(tenementMonthBean.getData());
                screenAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                misLoading();
            }
        });
    }

    /**
     * 此处获取年缴费传递的列表，如果列表为空，就需要重新抓取全部数据
     * 1：初次进入
     * 2：点击了左侧的全选按钮（将列表情况）
     */
    private void getData() {
        List<TenementMonthBean.DataBean> getList = (List<TenementMonthBean.DataBean>) in.getSerializableExtra("monthList");
        if (getList == null) {
            searchMonthData("0",false);//查询全部
            typePsi=0;
        } else {
            topList.clear();
            topList.addAll(getList);
            if (chooseNum == 0) {
                setChooseDo(false);//勾选
            } else if (chooseNum == allNum) {
                setChooseDo(true);//勾选
            }
            setChoose();//底部值计算
        }
    }

    private void setData() {
        topList = new ArrayList<>();
        listCommonAdapter = new ListCommonAdapter<TenementMonthBean.DataBean>(this, topList, R.layout.item_tenement_month) {
            @Override
            public void convert(ListCommonViewHolder helper, final TenementMonthBean.DataBean item, int position) {
                TextView tx_type = helper.getView(R.id.tx_type);
                TextView tx_address = helper.getView(R.id.tx_address);
                NoScrollListView lst_average = helper.getView(R.id.lst_average);
                tx_type.setText(item.getItem() + "");
                tx_address.setText(item.getItemAddress() + "");

                //服务器返回null，避免崩溃
                if (item.getBillMonthList() != null) {
                    secCommonAdapter = new ListCommonAdapter<TenementMonthBean.DataBean.BillMonthListBean>(TenementMonthActivity.this, item.getBillMonthList(), R.layout.item_month) {
                        @Override
                        public void convert(ListCommonViewHolder helper, final TenementMonthBean.DataBean.BillMonthListBean item, int position) {
                            TextView tx_month = helper.getView(R.id.tx_month);
                            ImageView img_check = helper.getView(R.id.img_check);
                            TextView tx_price = helper.getView(R.id.tx_price);
                            tx_month.setText(item.getBillMonth() + "");
                            tx_price.setText(getResources().getString(R.string.rmb) + decimalFormat.format(item.getTotalPrice()));
                            if (item.isChoose()) {
                                img_check.setImageResource(R.mipmap.check_theme);
                            } else {
                                img_check.setImageResource(R.mipmap.un_check_gray);
                            }
                            img_check.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (item.isChoose()) {
                                        addPrice = SubtractTwoValue(addPrice,item.getTotalPrice());
                                        --chooseNum;
                                    } else {
                                        addPrice = AddTwoValue(addPrice,item.getTotalPrice());
                                        ++chooseNum;
                                    }
                                    item.setChoose(!item.isChoose());
                                    setChoose();
                                }
                            });
                        }
                    };
                    lst_average.setAdapter(secCommonAdapter);
                    lst_average.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            in = new Intent(TenementMonthActivity.this, TenementOrderDetail.class);
                            in.putExtra("bean", item.getBillMonthList().get(position));
                            in.putExtra("item", item.getItem());
//                            in.putExtra("itemAddress", item.getItemAddress());
                            qStartActivity(in);
                        }
                    });
                }
            }
        };
        lst.setAdapter(listCommonAdapter);
    }

    /**
     * 设置全选or全部选
     */
    private void setChooseDo(boolean choose) {
        allNum = 0;
        chooseNum=0;
        addPrice=0;
        for (int i = 0, len = topList.size(); i < len; i++) {
            List<TenementMonthBean.DataBean.BillMonthListBean> payList = topList.get(i).getBillMonthList();
            for (int j = 0, lenj = payList.size(); j < lenj; j++) {
                payList.get(j).setChoose(choose);
                allNum++;
                if (choose) {
                    chooseNum++;
                    addPrice = AddTwoValue(payList.get(j).getTotalPrice(),addPrice);
                }
            }
        }
    }


    /**
     * item选中，底部总价，选中等处理
     */
    private void setChoose() {
        txChooseChild.setText("已选" + chooseNum + "项");
        txNeedPay.setText(Html.fromHtml("<font color=#666666>" + "合计：" + "</font>"
                + "<font color=#ff6e0b>" + getResources().getString(R.string.rmb) + decimalFormat.format(addPrice) + "</font>"));
        listCommonAdapter.notifyDataSetChanged();
        if (chooseNum == allNum&&allNum!=0) {
            imgCheck.setImageResource(R.mipmap.check_theme);
        } else {
            imgCheck.setImageResource(R.mipmap.un_check_gray);
        }

    }


    /**
     * 查询月份信息
     * @param code 筛选type
     * @param selectAll 是否全选列表
     */
    private void searchMonthData(String code,final boolean selectAll) {
        showLoading();
        HashMap<String, String> map = new HashMap<>();
        map.put("billYear", year + "");
        if (!TextUtils.isEmpty("code"))
            map.put("feeItemCode", code);
        map.put("enterpriseId", DataCacheManager.getInstance().getUser().getEnterpriseId());
        enqueue(createCallService(ServiceService.class).getPayMonthInfo(map), new RetrofitCallbackListener<TenementMonthBean>() {
            @Override
            public void onSuccess(Call<TenementMonthBean> call, TenementMonthBean tenementMonthBean) {
                misLoading();
                topList.clear();
                if (tenementMonthBean.getData() != null && tenementMonthBean.getData().size() > 0) {
                    topList.addAll(tenementMonthBean.getData());
                    listCommonAdapter.notifyDataSetChanged();
                    //可能年全选，月需要全部勾选
                    if (chooseNum == allNum||selectAll) {
                        setChooseDo(true);//勾选
                        setChoose();//底部值计算
                    }
                }else {
                    topList.clear();
                    listCommonAdapter.notifyDataSetChanged();
                    setChooseDo(false);//勾选
                    setChoose();//底部值计算
                }
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                misLoading();
            }
        });
    }

}
